package com.tbit.uqbike.webmanager.util.excel;


import com.tbit.uqbike.manager.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Collection;

/**
 * 包装类
 *
 * @param <T>
 * @author liuyazhuang
 */
@Slf4j
public class ExportExcelWrapper<T> extends ExportExcelUtil<T> {
    /**
     * <p>
     * 导出带有头部标题行的Excel <br>
     * 时间格式默认：yyyy-MM-dd hh:mm:ss <br>
     * </p>
     *
     * @param title   表格标题
     * @param headers 头部标题集合
     * @param dataset 数据集合
     * @param version 2003 或者 2007，不传时默认生成2003版本
     */
    public void exportExcel(String fileName, String title, String[] headers, Collection<T> dataset, HttpServletResponse response, String version) {
        exportExcel(fileName, title, headers, dataset, response, version, 20000);
    }

    public void exportExcel(String fileName, String title, String[] headers, Collection<T> dataset, HttpServletResponse response, String version, Integer maxSize) {
        if (dataset.size() > maxSize) {
            /**导出数据限制最大20000条*/
            throw new BaseException("ver.size.too.large");
        }
        try {
            response.setContentType("application/vnd.ms-excel");
            /*如果不替换，则会存在空格变成+号*/
            fileName = (URLEncoder.encode(fileName, "UTF-8") + ".xls").replaceAll("\\+", "%20");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            if (StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())) {
                exportExcel2003(title, headers, dataset, response.getOutputStream(), "yyyy-MM-dd HH:mm:ss");
            } else {
                exportExcel2007(title, headers, dataset, response.getOutputStream(), "yyyy-MM-dd HH:mm:ss");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
